package com.example.shuiyin.utils;

import com.example.shuiyin.constant.Constants;
import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

@Component
@RequiredArgsConstructor
@Slf4j
public class HttpUtils {
    
    private final RestTemplate restTemplate;

    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";

    /**
     * 获取重定向后的URL
     */
    public String getRedirectUrl(String url) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("User-Agent", USER_AGENT);
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, 
                HttpMethod.HEAD,
                null,
                String.class
            );
            
            if (response.getStatusCode().is3xxRedirection()) {
                return response.getHeaders().getLocation().toString();
            }
            
            return url;
        } catch (Exception e) {
            log.error("获取重定向URL失败: {}", e.getMessage(), e);
            return url;
        }
    }

    /**
     * 获取HTML内容
     */
    public String getHtml(String url) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("User-Agent", USER_AGENT);
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("获取HTML内容失败: {}", e.getMessage(), e);
            throw new AppException("获取HTML内容失败: " + e.getMessage(), ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 下载文件
     */
    public void downloadFile(String url, String targetPath) {
        try {
            URL website = new URL(url);
            try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                 FileOutputStream fos = new FileOutputStream(targetPath)) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
        } catch (IOException e) {
            log.error("下载文件失败: {}", e.getMessage(), e);
            throw new AppException("下载文件失败: " + e.getMessage(), ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }
} 